import React, { useState, useEffect, useRef } from 'react';
import {
    Table, Button, Modal, Form, Input, Select,
    Tag, Space, Avatar, Typography, Row, Col, Card
} from 'antd';
import './index.css';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { Meta } = Card;

// -------------------------- 原生日期工具函数 --------------------------
/** 检查是否为有效日期 */
const isDateValid = (date) => {
    return date instanceof Date && !isNaN(date.getTime());
};

/** 重置日期时间为当天0点 */
const resetTimeToZero = (date) => {
    if (!isDateValid(date)) return new Date();
    const newDate = new Date(date);
    newDate.setHours(0, 0, 0, 0);
    return newDate; // 确保返回修改后的新日期对象
};

/** 比较两个日期是否是同一天 */
const isSameDay = (date1, date2) => {
    if (!isDateValid(date1) || !isDateValid(date2)) return false;
    return date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate();
};

/** 格式化日期为YYYY-MM-DD字符串（适配原生date输入） */
const formatDateToString = (date) => {
    if (!isDateValid(date)) return '';
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

/** 解析日期字符串为Date对象 */
const parseDateString = (dateString) => {
    if (!dateString || typeof dateString !== 'string') return new Date();
    const parts = dateString.split('-');
    if (parts.length !== 3) return new Date();
    const date = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
    return isDateValid(date) ? date : new Date();
};

/** 格式化日期为"YYYY年MM月DD日"格式 */
const formatDateToChinese = (date) => {
    if (!isDateValid(date)) return '';
    return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日`;
};

const RowClass = () => {
    // 模拟员工数据（用于申请人选择）
    const employees = [
        { id: 1, name: '张前台', position: '前台接待', department: 'receptionist' },
        { id: 2, name: '李医师', position: '主治医师', department: 'physician' },
        { id: 3, name: '王助理', position: '医疗助理', department: 'assistant' },
        { id: 4, name: '赵前台', position: '前台接待', department: 'receptionist' }
    ];

    // 模拟排班时间数据（用于原排班时间选择）
    const shiftOptions = [
        { id: 1, time: '08:30-17:30（前台）', department: 'receptionist' },
        { id: 2, time: '09:00-16:00（前台）', department: 'receptionist' },
        { id: 3, time: '08:00-12:00（一号理疗室）', department: 'physician' },
        { id: 4, time: '13:00-17:00（一号理疗室）', department: 'physician' },
        { id: 5, time: '08:00-12:00（二号理疗室）', department: 'physician' },
        { id: 6, time: '13:00-17:00（二号理疗室）', department: 'physician' },
        { id: 7, time: '09:00-18:00（协助医师）', department: 'assistant' }
    ];

    // 日历状态管理
    const today = resetTimeToZero(new Date());
    const [currentDate, setCurrentDate] = useState(today);
    const [selectedDate, setSelectedDate] = useState(today);
    const [displayedWeekStart, setDisplayedWeekStart] = useState(() => {
        const dayOfWeek = today.getDay() || 7; // 转换为周一为1，周日为7
        const weekStart = new Date(today);
        weekStart.setDate(today.getDate() - (dayOfWeek - 1));
        return resetTimeToZero(weekStart);
    });
    const [calendarDays, setCalendarDays] = useState([]);

    // 筛选状态管理
    const [filters, setFilters] = useState({
        department: 'all',
        search: '',
        status: 'all'
    });

    // 弹窗状态管理
    const [isAdjustModalOpen, setIsAdjustModalOpen] = useState(false);
    const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
    const [isViewDetailsModalOpen, setIsViewDetailsModalOpen] = useState(false);
    const [isViewReasonModalOpen, setIsViewReasonModalOpen] = useState(false);
    const [currentApplicationId, setCurrentApplicationId] = useState(null);

    // 申请表单状态
    const [formData, setFormData] = useState({
        applicationId: '',
        employeeId: 1, // 默认选择第一个员工
        adjustDate: formatDateToString(today),
        originalShift: '08:30-17:30（前台）',
        targetShiftTime: '休息',
        targetShiftLocation: '前台',
        reason: '需要参加家庭聚会，已与同事协商代班'
    });

    // 排班申请数据
    const applicationData = useRef([
        {
            id: 1,
            applicant: '张前台',
            position: '前台接待',
            employeeId: 1,
            applyDate: '2024-05-15',
            adjustDate: '2024-05-16',
            originalShift: '08:30-17:30（前台）',
            targetShift: '休息',
            reason: '个人事务需处理，已与李前台协商代班',
            status: 'pending',
            approver: '',
            approveDate: '',
            comment: ''
        },
        {
            id: 2,
            applicant: '李医师',
            position: '主治医师',
            employeeId: 2,
            applyDate: '2024-05-14',
            adjustDate: '2024-05-20',
            originalShift: '08:00-12:00（一号理疗室）',
            targetShift: '13:00-17:00（一号理疗室）',
            reason: '上午有培训，与同事调换',
            status: 'approved',
            approver: '王主任',
            approveDate: '2024-05-15',
            comment: '同意调整'
        },
        {
            id: 3,
            applicant: '王助理',
            position: '医疗助理',
            employeeId: 3,
            applyDate: '2024-05-13',
            adjustDate: '2024-05-25',
            originalShift: '09:00-18:00（协助医师）',
            targetShift: '休息',
            reason: '家中有事需请假',
            status: 'rejected',
            approver: '王主任',
            approveDate: '2024-05-14',
            comment: '该时段人手紧张，无法批准'
        },
        {
            id: 4,
            applicant: '赵前台',
            position: '前台接待',
            employeeId: 4,
            applyDate: '2024-05-16',
            adjustDate: '2024-05-22',
            originalShift: '09:00-16:00（前台）',
            targetShift: '08:30-17:30（前台）',
            reason: '个人时间调整',
            status: 'pending',
            approver: '',
            approveDate: '',
            comment: ''
        },
        {
            id: 5,
            applicant: '张前台',
            position: '前台接待',
            employeeId: 1,
            applyDate: '2024-05-17',
            adjustDate: '2024-05-28',
            originalShift: '08:30-17:30（前台）',
            targetShift: '休息',
            reason: '周末有事',
            status: 'pending',
            approver: '',
            approveDate: '',
            comment: ''
        },
        {
            id: 6,
            applicant: '李医师',
            position: '主治医师',
            employeeId: 2,
            applyDate: '2024-05-18',
            adjustDate: '2024-06-01',
            originalShift: '13:00-17:00（一号理疗室）',
            targetShift: '08:00-12:00（一号理疗室）',
            reason: '下午有会议',
            status: 'approved',
            approver: '王主任',
            approveDate: '2024-05-19',
            comment: '同意调整'
        }
    ]);

    // 分页状态管理
    const [pagination, setPagination] = useState({
        current: 1,        // 当前页码
        pageSize: 3,       // 每页显示条数
        total: applicationData.current.length  // 总记录数
    });

    // 员工排班数据 - 包含在岗、休息、请假和申请调整四种状态
    const employeeScheduleData = [
        {
            timeSlot: '09:00-12:00',
            dailyAssignments: [
                { dateOffset: 0, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 1, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 2, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 3, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 4, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 5, name: '赵前台', status: 'leave', location: '请假' },
                { dateOffset: 6, name: '张前台', status: 'off', location: '休息' }
            ]
        },
        {
            timeSlot: '14:00-17:00',
            dailyAssignments: [
                { dateOffset: 0, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 1, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 2, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 3, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 4, name: '赵前台', status: 'off', location: '休息' },
                { dateOffset: 5, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 6, name: '赵前台', status: 'on', location: '前台' }
            ]
        },
        {
            timeSlot: '18:00-21:00',
            dailyAssignments: [
                { dateOffset: 0, name: '张前台', status: 'on', location: '前台' },
                { dateOffset: 1, name: '赵前台', status: 'leave', location: '请假' },
                { dateOffset: 2, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 3, name: '张前台', status: 'apply', location: '待审批' },
                { dateOffset: 4, name: '赵前台', status: 'on', location: '前台' },
                { dateOffset: 5, name: '张前台', status: 'off', location: '休息' },
                { dateOffset: 6, name: '赵前台', status: 'on', location: '前台' }
            ]
        }
    ];

    // 初始化日历并输出默认选中的日期范围
    useEffect(() => {
        renderCalendar();
        updateFormDate();
    }, []);

    // 当显示的周或月份变化时重新渲染日历（修复关键：添加currentDate依赖）
    useEffect(() => {
        renderCalendar();
        updateDateRangeDisplay();
        logDateRange();
    }, [displayedWeekStart, currentDate]);

    // 当申请数据变化时更新分页总数
    useEffect(() => {
        setPagination(prev => ({
            ...prev,
            total: applicationData.current.length
        }));
    }, [applicationData.current]);

    // 更新表单默认日期
    const updateFormDate = () => {
        setFormData(prev => ({
            ...prev,
            adjustDate: formatDateToString(selectedDate)
        }));
    };

    // 渲染日历
    const renderCalendar = () => {
        if (!isDateValid(currentDate)) return;

        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();

        // 获取月份的第一天和最后一天
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);

        // 获取月份第一天是星期几 (0是星期日)
        const firstDayOfWeek = firstDay.getDay();

        // 获取上个月的最后几天
        const prevMonth = new Date(year, month, 0);
        const prevMonthDays = firstDayOfWeek;

        const days = [];

        // 上个月的日期
        for (let i = prevMonthDays - 1; i >= 0; i--) {
            const dayNum = prevMonth.getDate() - i;
            const date = new Date(prevMonth.getFullYear(), prevMonth.getMonth(), dayNum);
            resetTimeToZero(date);
            days.push(createDayElement(dayNum, true, date));
        }

        // 当前月的日期
        for (let i = 1; i <= lastDay.getDate(); i++) {
            const date = new Date(year, month, i);
            resetTimeToZero(date);
            days.push(createDayElement(i, false, date));
        }

        // 下个月的日期
        const totalDays = prevMonthDays + lastDay.getDate();
        const nextMonthDays = 42 - totalDays; // 6行7列 = 42个格子

        for (let i = 1; i <= nextMonthDays; i++) {
            const date = new Date(year, month + 1, i);
            resetTimeToZero(date);
            days.push(createDayElement(i, true, date));
        }

        setCalendarDays(days);
    };

    // 创建日历日期元素
    const createDayElement = (dayNum, isDisabled, date) => {
        if (!isDateValid(date)) return null;

        // 检查是否是今天
        const today = resetTimeToZero(new Date());
        const isToday = !isDisabled && isSameDay(date, today);

        // 检查是否在当前显示的周范围内
        const isInCurrentWeek = !isDisabled && isDateInCurrentWeek(date);

        // 检查是否是选中的日期
        const isSelected = !isDisabled && isSameDay(date, selectedDate);

        return (
            <div
                key={date.toISOString()}
                className={`calendar-day ${isDisabled ? 'calendar-day-disabled' : ''} 
                           ${isToday ? 'calendar-day-today' : ''} 
                           ${isInCurrentWeek ? 'calendar-day-range' : ''}
                           ${isSelected ? 'calendar-day-selected' : ''}
                           `}
                onClick={() => !isDisabled && handleDateSelect(date)}
            >
                {dayNum}
            </div>
        );
    };

    // 处理日期选择
    const handleDateSelect = (date) => {
        if (!isDateValid(date)) return;

        const newDate = resetTimeToZero(new Date(date));
        setSelectedDate(newDate);

        // 更新周范围
        const dayOfWeek = newDate.getDay() || 7; // 转换为周一为1，周日为7
        const weekStart = new Date(newDate);
        weekStart.setDate(newDate.getDate() - (dayOfWeek - 1));
        resetTimeToZero(weekStart);
        setDisplayedWeekStart(weekStart);

        // 更新表单日期
        setFormData(prev => ({
            ...prev,
            adjustDate: formatDateToString(newDate)
        }));
    };

    // 打印当前选中的日期间隔到控制台
    const logDateRange = () => {
        if (!isDateValid(displayedWeekStart)) return;

        const weekStart = new Date(displayedWeekStart);
        const weekEnd = new Date(displayedWeekStart);
        weekEnd.setDate(displayedWeekStart.getDate() + 6);

        const startStr = formatDateToChinese(weekStart);
        const endStr = formatDateToChinese(weekEnd);

        console.log(`选中的日期间隔: ${startStr} 到 ${endStr}`);
    };

    // 检查日期是否在当前显示的周范围内
    const isDateInCurrentWeek = (date) => {
        if (!isDateValid(date) || !isDateValid(displayedWeekStart)) return false;

        // 重置周开始和结束的时间
        const weekStart = resetTimeToZero(new Date(displayedWeekStart));

        const weekEnd = new Date(displayedWeekStart);
        weekEnd.setDate(weekEnd.getDate() + 6);
        weekEnd.setHours(23, 59, 59, 999);

        // 重置目标日期的时间
        const targetDate = resetTimeToZero(new Date(date));

        return targetDate >= weekStart && targetDate <= weekEnd;
    };

    // 更新日期范围显示
    const updateDateRangeDisplay = () => {
        if (!isDateValid(displayedWeekStart)) return '';

        const weekEnd = new Date(displayedWeekStart);
        weekEnd.setDate(displayedWeekStart.getDate() + 6);

        const startMonth = displayedWeekStart.getMonth() + 1;
        const startDay = displayedWeekStart.getDate();
        const endMonth = weekEnd.getMonth() + 1;
        const endDay = weekEnd.getDate();

        return startMonth === endMonth
            ? `${startMonth}月${startDay}日 - ${endDay}日`
            : `${startMonth}月${startDay}日 - ${endMonth}月${endDay}日`;
    };

    // 切换到上一个月
    const handlePrevMonth = () => {
        setCurrentDate(prev => {
            if (!isDateValid(prev)) return new Date();
            const newDate = new Date(prev);
            newDate.setMonth(prev.getMonth() - 1);
            return newDate;
        });
    };

    // 切换到下一个月
    const handleNextMonth = () => {
        setCurrentDate(prev => {
            if (!isDateValid(prev)) return new Date();
            const newDate = new Date(prev);
            newDate.setMonth(prev.getMonth() + 1);
            return newDate;
        });
    };

    // 回到今天
    const handleToday = () => {
        const today = resetTimeToZero(new Date());
        setCurrentDate(today);
        setSelectedDate(today);

        // 更新周范围
        const dayOfWeek = today.getDay() || 7; // 转换为周一为1，周日为7
        const weekStart = new Date(today);
        weekStart.setDate(today.getDate() - (dayOfWeek - 1));
        resetTimeToZero(weekStart);
        setDisplayedWeekStart(weekStart);
    };

    // 打开调整排班弹窗
    const openAdjustModal = () => {
        setFormData(prev => ({
            ...prev,
            applicationId: '',
            employeeId: 1, // 默认选择第一个员工
            adjustDate: formatDateToString(selectedDate),
            originalShift: '08:30-17:30（前台）',
            targetShiftTime: '休息',
            targetShiftLocation: '前台',
            reason: '需要参加家庭聚会，已与同事协商代班'
        }));
        setIsAdjustModalOpen(true);
    };

    // 根据员工ID获取员工信息
    const getEmployeeById = (id) => {
        return employees.find(emp => emp.id === id) || employees[0];
    };

    // 处理申请操作
    const handleApplicationAction = (action, id) => {
        setCurrentApplicationId(id);

        switch (action) {
            case 'cancel':
                setIsCancelModalOpen(true);
                break;
            case 'edit':
                if (Array.isArray(applicationData.current)) {
                    const numericId = typeof id === 'number' ? id : parseInt(id, 10);
                    const application = applicationData.current.find(item => item.id === numericId);

                    if (application) {
                        setFormData({
                            applicationId: application.id.toString(),
                            employeeId: application.employeeId || 1,
                            adjustDate: application.adjustDate,
                            originalShift: application.originalShift,
                            targetShiftTime: application.targetShift === '休息'
                                ? '休息'
                                : application.targetShift.split('（')[0],
                            targetShiftLocation: application.targetShift === '休息'
                                ? '前台'
                                : application.targetShift.split('（')[1]?.replace('）', '') || '前台',
                            reason: application.reason
                        });
                        setIsAdjustModalOpen(true);
                    } else {
                        console.error('未找到对应的申请记录', id);
                        alert('未找到对应的申请记录');
                    }
                } else {
                    console.error('applicationData.current 不是一个数组');
                }
                break;
            case 'view':
                setIsViewDetailsModalOpen(true);
                break;
            case 'reapply':
                if (Array.isArray(applicationData.current)) {
                    const numericId = typeof id === 'number' ? id : parseInt(id, 10);
                    const appToReapply = applicationData.current.find(item => item.id === numericId);

                    if (appToReapply) {
                        setFormData({
                            applicationId: '',
                            employeeId: appToReapply.employeeId || 1,
                            adjustDate: appToReapply.adjustDate,
                            originalShift: appToReapply.originalShift,
                            targetShiftTime: appToReapply.targetShift === '休息'
                                ? '休息'
                                : appToReapply.targetShift.split('（')[0],
                            targetShiftLocation: appToReapply.targetShift === '休息'
                                ? '前台'
                                : appToReapply.targetShift.split('（')[1]?.replace('）', '') || '前台',
                            reason: appToReapply.reason
                        });
                        setIsAdjustModalOpen(true);
                    }
                }
                break;
            case 'view-reason':
                setIsViewReasonModalOpen(true);
                break;
        }
    };

    // 提交排班调整申请
    const handleSubmitAdjustment = (e) => {
        e.preventDefault();

        // 验证日期格式
        const date = parseDateString(formData.adjustDate);
        if (!isDateValid(date)) {
            alert('请选择有效的调整日期');
            return;
        }

        // 获取当前选中的员工信息
        const employee = getEmployeeById(formData.employeeId);

        if (formData.applicationId) {
            // 编辑现有申请
            const index = applicationData.current.findIndex(
                item => item.id === parseInt(formData.applicationId)
            );

            if (index !== -1) {
                applicationData.current[index] = {
                    ...applicationData.current[index],
                    applicant: employee.name,
                    position: employee.position,
                    employeeId: formData.employeeId,
                    adjustDate: formData.adjustDate,
                    originalShift: formData.originalShift,
                    targetShift: formData.targetShiftTime === '休息'
                        ? '休息'
                        : `${formData.targetShiftTime}（${formData.targetShiftLocation}）`,
                    reason: formData.reason
                };
            }
            alert('排班调整申请已更新');
        } else {
            // 创建新申请
            const newId = Math.max(...applicationData.current.map(item => item.id), 0) + 1;
            applicationData.current.push({
                id: newId,
                applicant: employee.name,
                position: employee.position,
                employeeId: formData.employeeId,
                applyDate: formatDateToString(new Date()),
                adjustDate: formData.adjustDate,
                originalShift: formData.originalShift,
                targetShift: formData.targetShiftTime === '休息'
                    ? '休息'
                    : `${formData.targetShiftTime}（${formData.targetShiftLocation}）`,
                reason: formData.reason,
                status: 'pending',
                approver: '',
                approveDate: '',
                comment: ''
            });
            alert('排班调整申请已提交，等待管理员审批');
        }

        closeAllModals();
    };

    // 关闭所有弹窗
    const closeAllModals = () => {
        setIsAdjustModalOpen(false);
        setIsCancelModalOpen(false);
        setIsViewDetailsModalOpen(false);
        setIsViewReasonModalOpen(false);
        setCurrentApplicationId(null);
    };

    // 处理表单输入变化
    const handleFormChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    // 确认撤销申请
    const confirmCancelApplication = () => {
        if (currentApplicationId !== null) {
            applicationData.current = applicationData.current.filter(
                item => item.id !== currentApplicationId
            );
            alert('申请已成功撤销');
        }
        closeAllModals();
    };

    // 格式化日期显示
    const formatDate = (dateString) => {
        if (!dateString) return '';

        // 处理日期范围的情况
        if (dateString.includes('至')) {
            const [start, end] = dateString.split('至');
            return `${formatSingleDate(start)}至${formatSingleDate(end)}`;
        }

        return formatSingleDate(dateString);
    };

    // 格式化单个日期
    const formatSingleDate = (dateString) => {
        const date = parseDateString(dateString);
        if (!isDateValid(date)) return '';

        const month = date.getMonth() + 1;
        const day = date.getDate();

        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const weekday = weekdays[date.getDay()];

        return `${month}月${day}日（${weekday}）`;
    };

    // 获取当前查看的申请详情
    const getCurrentApplication = () => {
        return applicationData.current.find(item => item.id === currentApplicationId) || {};
    };

    // 处理筛选条件变化
    const handleFilterChange = (filterName, value) => {
        setFilters(prev => ({
            ...prev,
            [filterName]: value
        }));
    };

    // 清除所有筛选条件
    const clearAllFilters = () => {
        setFilters({
            department: 'all',
            search: '',
            status: 'all'
        });
    };

    // 筛选员工数据
    const filteredEmployees = () => {
        // 对于按时间段组织的数据，只筛选前台相关人员
        return employeeScheduleData.filter(item => {
            // 部门筛选 - 只显示前台
            if (filters.department !== 'all' && filters.department !== 'receptionist') {
                return false;
            }

            // 搜索筛选
            if (filters.search) {
                const hasMatchingName = item.dailyAssignments.some(
                    assignment => assignment.name.includes(filters.search)
                );
                if (!hasMatchingName) {
                    return false;
                }
            }

            // 状态筛选
            if (filters.status !== 'all') {
                const hasMatchingStatus = item.dailyAssignments.some(
                    assignment => assignment.status === filters.status
                );
                if (!hasMatchingStatus) {
                    return false;
                }
            }

            return true;
        });
    };

    // 处理分页变化
    const handleTableChange = (paginationChange) => {
        setPagination({
            ...pagination,
            current: paginationChange.current,
            pageSize: paginationChange.pageSize
        });
    };

    // 获取分页后的数据
    const getPagedApplications = () => {
        const { current, pageSize } = pagination;
        const startIndex = (current - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        return applicationData.current.slice(startIndex, endIndex);
    };

    // 获取当前申请数据
    const currentApp = getCurrentApplication();

    // 员工排班表列定义 - 包含所有状态显示
    const scheduleColumns = [
        {
            title: '时间段',
            dataIndex: 'timeSlot',
            key: 'timeSlot',
            width: 120,
            render: (text) => (
                <div className="font-medium text-sm text-center py-2">
                    {text}
                </div>
            ),
            align: 'center'
        },
        // 生成日期列并过滤空值
        ...Array.from({ length: 7 }, (_, i) => {
            if (!isDateValid(displayedWeekStart)) return null;

            const currentDate = new Date(displayedWeekStart);
            currentDate.setDate(displayedWeekStart.getDate() + i);

            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            const dayOfWeek = currentDate.getDay();
            const month = currentDate.getMonth() + 1;
            const day = currentDate.getDate();

            return {
                title: (
                    <div className="flex flex-col items-center text-center">
                        <span className="text-xs">{weekdays[dayOfWeek]}</span>
                        <span className="text-[10px] mt-1">{month}/{day}</span>
                    </div>
                ),
                key: `day-${i}`,
                width: 180,
                render: (_, record) => {
                    const assignment = record.dailyAssignments.find(
                        a => a.dateOffset === i
                    );

                    if (!assignment) return (
                        <div className="flex items-center justify-center h-12"></div>
                    );

                    return (
                        <div className="flex items-center justify-center py-2">
                            <Tag
                                color={
                                    assignment.status === 'on' ? 'green' :
                                        assignment.status === 'off' ? 'gray' :
                                            assignment.status === 'leave' ? 'red' : 'orange'
                                }
                                className="text-center"
                            >
                                {assignment.name}
                            </Tag>
                        </div>
                    );
                },
                align: 'center'
            };
        }).filter(col => col !== null) // 过滤可能的null值
    ];

    // 申请记录列定义
    const applicationColumns = [
        {
            title: '申请人',
            dataIndex: 'applicant',
            key: 'applicant',
            render: (text, record) => (
                <div className="flex items-center">
                    <Avatar icon={
                        record.position === '前台接待' ? <i className="fa fa-user"></i> :
                            record.position === '主治医师' ? <i className="fa fa-user-md"></i> :
                                <i className="fa fa-user-plus"></i>
                    } className="mr-2" size="small" />
                    <span className="text-sm">{text}（{record.position}）</span>
                </div>
            )
        },
        {
            title: '调整日期',
            dataIndex: 'adjustDate',
            key: 'adjustDate',
            render: (text) => formatDate(text)
        },
        {
            title: '原排班',
            dataIndex: 'originalShift',
            key: 'originalShift'
        },
        {
            title: '申请调整为',
            dataIndex: 'targetShift',
            key: 'targetShift'
        },
        {
            title: '申请原因',
            dataIndex: 'reason',
            key: 'reason',
            ellipsis: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'orange';
                let text = '待审批';

                if (status === 'approved') {
                    color = 'green';
                    text = '已批准';
                } else if (status === 'rejected') {
                    color = 'red';
                    text = '已拒绝';
                }

                return <Tag color={color}>{text}</Tag>;
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="small">
                    {record.status === 'pending' ? (
                        <>
                            <Button
                                icon={<i className="fa fa-trash-o"></i>}
                                size="small"
                                type="text"
                                danger
                                onClick={() => handleApplicationAction('cancel', record.id)}
                            >
                                撤销
                            </Button>
                            <Button
                                icon={<i className="fa fa-pencil"></i>}
                                size="small"
                                type="text"
                                onClick={() => handleApplicationAction('edit', record.id)}
                            >
                                编辑
                            </Button>
                        </>
                    ) : record.status === 'approved' ? (
                        <Button
                            icon={<i className="fa fa-eye"></i>}
                            size="small"
                            type="text"
                            onClick={() => handleApplicationAction('view', record.id)}
                        >
                            查看详情
                        </Button>
                    ) : (
                        <>
                            <Button
                                icon={<i className="fa fa-plus"></i>}
                                size="small"
                                type="text"
                                onClick={() => handleApplicationAction('reapply', record.id)}
                            >
                                重新申请
                            </Button>
                            <Button
                                icon={<i className="fa fa-eye"></i>}
                                size="small"
                                type="text"
                                onClick={() => handleApplicationAction('view-reason', record.id)}
                            >
                                查看原因
                            </Button>
                        </>
                    )}
                </Space>
            )
        }
    ];

    return (
        <main className="rowclass">
            {/* 页面标题与操作区 */}
            <Card className="mb-6" bordered={false}>
                <Row justify="space-between" align="middle">
                    <Col>
                        <Title level={2} className="text-primary">排班管理</Title>
                        <Paragraph className="text-gray-600 mt-1">
                            <i className="fa fa-calendar-check-o mr-1.5 text-secondary"></i>
                            查看值班详情、提交调整申请
                        </Paragraph>
                    </Col>
                    <Col>
                        <Button
                            onClick={openAdjustModal}
                            type="primary"
                            className="bg-secondary"
                        >
                            <i className="fa fa-pencil-square-o mr-1.5"></i> 申请调整排班
                        </Button>
                    </Col>
                </Row>
            </Card>

            {/* 日期选择器与排班概览 */}
            <Card className="mb-8" bordered={false}>
                <Row justify="space-between" align="middle" className="mb-6">
                    <Col>
                        <Space>
                            <Button
                                onClick={handlePrevMonth}
                                size="small"
                                type="text"
                            >
                                <i className="fa fa-chevron-left"></i>
                            </Button>
                            <Text strong>
                                {isDateValid(currentDate) ? `${currentDate.getFullYear()}年${currentDate.getMonth() + 1}月` : ''}
                            </Text>
                            <Button
                                onClick={handleNextMonth}
                                size="small"
                                type="text"
                            >
                                <i className="fa fa-chevron-right"></i>
                            </Button>
                            <Button
                                onClick={handleToday}
                                size="small"
                                type="default"
                                className="bg-secondary/10 text-secondary border-secondary/20"
                            >
                                <i className="fa fa-calendar mr-1"></i> 今天
                            </Button>
                        </Space>
                    </Col>
                    <Col>
                        <Space>
                            <Button type="primary" size="small" className="bg-secondary">
                                月视图
                            </Button>
                        </Space>
                    </Col>
                </Row>

                {/* 周历选择器 */}
                <div className="mb-6">
                    {/* 星期标题 */}
                    <div className="calendar-grid mb-2">
                        <div className="text-center text-xs text-gray-500">周日</div>
                        <div className="text-center text-xs text-gray-500">周一</div>
                        <div className="text-center text-xs text-gray-500">周二</div>
                        <div className="text-center text-xs text-gray-500">周三</div>
                        <div className="text-center text-xs text-gray-500">周四</div>
                        <div className="text-center text-xs text-gray-500">周五</div>
                        <div className="text-center text-xs text-gray-500">周六</div>
                    </div>

                    {/* 日历格子容器 */}
                    <div className="calendar-week min-h-[120px]">
                        {calendarDays}
                    </div>
                </div>

                {/* 日期概览信息 - 明确展示四种状态 */}
                <Row gutter={[16, 16]}>
                    <Col>
                        <div className="flex items-center bg-light px-4 py-2.5 rounded-lg">
                            <div className="w-3 h-3 rounded-full bg-status-on mr-2"></div>
                            <span className="text-sm">在岗</span>
                        </div>
                    </Col>
                    <Col>
                        <div className="flex items-center bg-light px-4 py-2.5 rounded-lg">
                            <div className="w-3 h-3 rounded-full bg-status-off mr-2"></div>
                            <span className="text-sm">休息</span>
                        </div>
                    </Col>
                    <Col>
                        <div className="flex items-center bg-light px-4 py-2.5 rounded-lg">
                            <div className="w-3 h-3 rounded-full bg-status-leave mr-2"></div>
                            <span className="text-sm">请假</span>
                        </div>
                    </Col>
                    <Col>
                        <div className="flex items-center bg-light px-4 py-2.5 rounded-lg">
                            <div className="w-3 h-3 rounded-full bg-status-apply mr-2"></div>
                            <span className="text-sm">申请调整</span>
                        </div>
                    </Col>
                    <Col flex="auto" />
                    <Col>
                        <div className="bg-primary/5 px-4 py-2.5 rounded-lg">
                            <span className="text-sm font-medium">当前查看: {updateDateRangeDisplay()}</span>
                        </div>
                    </Col>
                </Row>
            </Card>

            {/* 员工排班表 */}
            <Card className="mb-8" bordered={false}>
                <Row justify="space-between" align="middle" className="mb-6">
                    <Col>
                        <Title level={3} className="text-primary">前台排班表</Title>

                    </Col>
                    <Col>
                        <Space>
                            <Button icon={<i className="fa fa-download"></i>} size="small" type="text">
                                导出
                            </Button>
                            <Button icon={<i className="fa fa-print"></i>} size="small" type="text">
                                打印
                            </Button>
                        </Space>
                    </Col>
                </Row>

                {/* 排班表 */}
                <Table
                    columns={scheduleColumns}
                    dataSource={filteredEmployees()}
                    pagination={false}
                    bordered

                />
            </Card>

            {/* 排班调整申请记录 */}
            <Card className="mb-8" bordered={false}>
                <Row justify="space-between" align="middle" className="mb-6">
                    <Col>
                        <Title level={3} className="text-primary">排班调整申请记录</Title>
                    </Col>
                </Row>

                <Table
                    columns={applicationColumns}
                    dataSource={getPagedApplications()}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条记录`,
                        pageSizeOptions: ['3', '5', '10'],
                        size: 'middle'
                    }}
                    onChange={handleTableChange}
                    bordered
                    rowKey="id"
                />
            </Card>

            {/* 排班调整申请弹窗 */}
            <Modal
                title={formData.applicationId ? '编辑排班调整申请' : '申请调整排班'}
                open={isAdjustModalOpen}
                onCancel={closeAllModals}
                footer={[
                    <Button key="cancel" onClick={closeAllModals}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleSubmitAdjustment} className="bg-secondary">
                        提交申请
                    </Button>
                ]}
                width={600}
            >
                <Form layout="vertical">
                    <Form.Item label="申请人" required>
                        <Select
                            value={formData.employeeId}
                            onChange={(value) => {
                                setFormData(prev => ({
                                    ...prev,
                                    employeeId: value,
                                    // 当切换员工时，自动选择该员工所在部门的默认排班
                                    originalShift: shiftOptions.find(
                                        s => s.department === getEmployeeById(value).department
                                    )?.time || prev.originalShift
                                }));
                            }}
                            style={{ width: '100%' }}
                        >
                            {employees.map(emp => (
                                <Option key={emp.id} value={emp.id}>
                                    {emp.name}（{emp.position}）
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item label="调整日期" required>
                        <Input
                            type="date"
                            value={formData.adjustDate}
                            onChange={(e) => {
                                setFormData(prev => ({
                                    ...prev,
                                    adjustDate: e.target.value
                                }));
                            }}
                            style={{ width: '100%' }}
                        />
                    </Form.Item>

                    <Form.Item label="原排班时间" required>
                        <Select
                            value={formData.originalShift}
                            onChange={(value) => {
                                setFormData(prev => ({ ...prev, originalShift: value }));
                            }}
                            style={{ width: '100%' }}
                        >
                            {/* 根据选中的员工部门筛选排班选项 */}
                            {shiftOptions
                                .filter(shift => shift.department === getEmployeeById(formData.employeeId).department)
                                .map(shift => (
                                    <Option key={shift.id} value={shift.time}>
                                        {shift.time}
                                    </Option>
                                ))}
                        </Select>
                    </Form.Item>

                    <Row gutter={[16, 16]}>
                        <Col xs={24} sm={12}>
                            <Form.Item label="申请调整为" required>
                                <Select
                                    name="targetShiftTime"
                                    value={formData.targetShiftTime}
                                    onChange={(value) => {
                                        setFormData(prev => ({ ...prev, targetShiftTime: value }));
                                    }}
                                    style={{ width: '100%' }}
                                >
                                    <Option value="休息">休息</Option>
                                    <Option value="08:30-17:30">08:30-17:30</Option>
                                    <Option value="09:00-16:00">09:00-16:00</Option>
                                    <Option value="13:00-21:00">13:00-21:00</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={12}>
                            <Form.Item label="工作地点" required>
                                <Select
                                    name="targetShiftLocation"
                                    value={formData.targetShiftLocation}
                                    onChange={(value) => {
                                        setFormData(prev => ({ ...prev, targetShiftLocation: value }));
                                    }}
                                    style={{ width: '100%' }}
                                >
                                    <Option value="前台">前台</Option>
                                    <Option value="一号理疗室（协助）">一号理疗室（协助）</Option>
                                    <Option value="二号理疗室（协助）">二号理疗室（协助）</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item label="申请原因" required>
                        <Input.TextArea
                            name="reason"
                            rows={3}
                            placeholder="请填写调整原因..."
                            value={formData.reason}
                            onChange={handleFormChange}
                        />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 其他弹窗保持不变 */}
            <Modal
                title="确认撤销申请"
                open={isCancelModalOpen}
                onCancel={closeAllModals}
                footer={[
                    <Button key="cancel" onClick={closeAllModals}>
                        取消
                    </Button>,
                    <Button key="confirm" type="primary" danger onClick={confirmCancelApplication}>
                        确认撤销
                    </Button>
                ]}
            >
                <Paragraph>
                    您确定要撤销此排班调整申请吗？撤销后将无法恢复，请谨慎操作。
                </Paragraph>
            </Modal>

            <Modal
                title="申请详情"
                open={isViewDetailsModalOpen}
                onCancel={closeAllModals}
                footer={[
                    <Button key="close" onClick={closeAllModals}>
                        关闭
                    </Button>
                ]}
            >
                <div className="space-y-4">
                    <Row>
                        <Col span={6}><Text type="secondary">申请人</Text></Col>
                        <Col span={18}>{currentApp.applicant}（{currentApp.position}）</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">申请日期</Text></Col>
                        <Col span={18}>{formatDate(currentApp.applyDate)}</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">调整日期</Text></Col>
                        <Col span={18}>{formatDate(currentApp.adjustDate)}</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">原排班</Text></Col>
                        <Col span={18}>{currentApp.originalShift}</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">申请调整为</Text></Col>
                        <Col span={18}>{currentApp.targetShift}</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">申请原因</Text></Col>
                        <Col span={18}>{currentApp.reason}</Col>
                    </Row>
                    <Row>
                        <Col span={6}><Text type="secondary">审批状态</Text></Col>
                        <Col span={18}>
                            <Tag color={
                                currentApp.status === 'pending' ? 'orange' :
                                    currentApp.status === 'approved' ? 'green' : 'red'
                            }>
                                {currentApp.status === 'pending' ? '待审批' :
                                    currentApp.status === 'approved' ? '已批准' : '已拒绝'}
                            </Tag>
                        </Col>
                    </Row>
                    {currentApp.status !== 'pending' && (
                        <>
                            <Row>
                                <Col span={6}><Text type="secondary">审批人</Text></Col>
                                <Col span={18}>{currentApp.approver}</Col>
                            </Row>
                            <Row>
                                <Col span={6}><Text type="secondary">审批日期</Text></Col>
                                <Col span={18}>{formatDate(currentApp.approveDate)}</Col>
                            </Row>
                            {currentApp.comment && (
                                <Row>
                                    <Col span={6}><Text type="secondary">审批意见</Text></Col>
                                    <Col span={18}>{currentApp.comment}</Col>
                                </Row>
                            )}
                        </>
                    )}
                </div>
            </Modal>

            <Modal
                title="拒绝原因"
                open={isViewReasonModalOpen}
                onCancel={closeAllModals}
                footer={[
                    <Button key="close" onClick={closeAllModals}>
                        我知道了
                    </Button>
                ]}
            >
                <div className="bg-red-50 p-4 rounded-lg mb-5">
                    <Text type="danger">
                        {currentApp.comment || '未提供拒绝原因'}
                    </Text>
                </div>
            </Modal>
        </main>
    );
};

export default RowClass;
